import Router from '../../utils/router';
import base from '../../config/base.js';
import service from '../../services/groupdragon';
import Record from '../../utils/page-record.js';
import Record_server from '../../services/record-stat';
var scrollTime = null;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    icon_play: base.static + 'store/play2.png',
    icon_group: base.static + 'groupdragon/groupdDragon2.png',
    icon_mygroup: base.static + 'groupdragon/myFree1.png',
    icon_next: base.static + 'collage/next.png',
    icon_mask_sellout: base.static + 'collage/out.png',
    icon_no_avater: base.static + '/free/head.png',
    incn_active_end: base.static + '/groupdragon/active-end.png',
    store_id: '',
    user_id: '',
    groupList: [], //群接龙
    endGroupBloon: true, //群接龙事件节流
    loadGroupBloon: true, //群接龙是否到底
    nomore: true, //群接龙是否没有
    pageGroup: 0, //群接龙页数
    swiperList: '', //轮播
    isShenhe: '', //审核开关
    hottodyList: [], // 2.12.0今日热销
    pageHot: 0,
    endHotBloon: true,
    loadHotBloon: true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    let user_info = wx.getStorageSync('user_info') || {id:'',lastView:{seid:''}};
    that.setData({
      store_id: user_info.lastView.seid,
      user_id: user_info.id,
      isShenhe: wx.getStorageSync('isShenhe')
    })
    if (options.method && options.method == 'navigateBack') {
    } else {
      that.getGroupList(1);
      that.swiperGroup();
    }

  },
  // 免费拿轮播
  swiperGroup: function () {
    let that = this;
    let params = {}
    service.shufflingorder(params, function (res) {
      if (res.code && res.code == 1) {
        that.setData({
          swiperList: res.data
        })
      }
    });
    wx.stopPullDownRefresh()
  },
  //群接龙列表
  getGroupList: function (page) {
    let that = this;
    let params = {
      store_id: that.data.store_id,
      page: page,
      limit: 10
    }
    service.groupgoodslist(params, function (res) {
      if (res.code && res.code == 1) {
        let grouplist = that.data.groupList.concat(res.data.list);
        if (grouplist != "") {//定时器
          let myDate = new Date();
          let hours = 23 - myDate.getHours()
          grouplist.forEach((item, index) => {
            if (item.all_num_status == 1) {//有库存
              let floor1 = hours * 3600;
              let floor2 = (hours + 24) * 3600
              let time = item.time
              if (item.time <= floor1) {
                let strArr = item.validity_end_time.split("-");
                grouplist[index].time_str = '今日' + strArr[2].split(' ')[1];
              } else if (floor1 < item.time && item.time < floor2) {
                let strArr = item.validity_end_time.split("-");
                grouplist[index].time_str = '明日' + strArr[2].split(' ')[1];
              } else if (item.time > floor2) {
                let strArr = item.validity_end_time.split("-");
                grouplist[index].time_str = strArr[1] + '月' + strArr[2].split(' ')[0] + '日' + strArr[2].split(' ')[1];
              }
            }
          })
        }
        that.setData({
          groupList: grouplist,
          pageGroup: page + 1,
          endGroupBloon: true,
        })
        // 是否显示没有更多
        if (grouplist.length >= res.data.count) {
          that.setData({
            loadGroupBloon: false,
          })
          that.storeListHot(1)
        }
      }
    });
    wx.stopPullDownRefresh()
  },
  // 今日热销列表
  storeListHot: function (page) {
    let that = this;
    let params = {
      page: page,
      per_page: 10
    }
    service.customerRecommend(params, function (res) {
      if (res && res.code == 200) {
        let stolistHot = that.data.hottodyList.concat(res.data.recommend);
        that.setData({
          hottodyList: stolistHot,
          pageHot: page + 1,
          endHotBloon: true
        });
        //是否到底
        if (stolistHot.length == res.data.count) {
          that.setData({
            loadHotBloon: false,
            nomore: false,
          })
        }
      }
      wx.stopPullDownRefresh();
    });
  },
  // 点击底部选项卡
  chooseTab: function (e) {
    let that = this;
    Router.go('mygroup', ``, 'redirectTo')
  },
  //阻止swipeer手滑
  stopTouchMove: function () {
    return false
  },
  // 去首页
  goStore: function () {
    Router.go('store', `store_id=${this.data.store_id}`)
  },
  // 去规则
  goWeb: function () {
    let url = encodeURIComponent('https://kpxd.zhengdianhaohuo.com/h5/#/active/win3_825')
    Router.go('web', `url=${url}`)
  },
  //去群接龙详情
  goGroupDetail: function (e) {
    let that = this;
    let allnumstatus = e.currentTarget.dataset.allnumstatus;
    let goods_id = e.currentTarget.id;
    if (allnumstatus == 1 ){
      Router.go("dragon", `store_id=${that.data.store_id}&segsid=${e.currentTarget.dataset.segsid}`);
    }
    that.viewRecord(goods_id, 'click')
  },
  //监听页面高度
  scrollTimer: null,
  onPageScroll: function (e) {
    let that = this;
    if (that.scrollTimer) {
      clearTimeout(that.scrollTimer)
    };
    that.scrollTimer = setTimeout(() => {
      that.setData({
        scrolltop: e.scrollTop
      })
      that.queryMultipleNodes(e.scrollTop)
    }, 500);
  },
  queryMultipleNodes(scroll) {
    let that = this;
    let query = wx.createSelectorQuery();
    let scrolls = 0;
    let index = 0;
    let s = wx.getSystemInfoSync().windowHeight;
    query.selectAll('.test').boundingClientRect(function (rects) {
      if (scrolls < scroll) {
        for (let i = index, len = rects.length; i < len; i++) {
          let rect = rects[i];
          if (rect && 0 < rect.top && rect.bottom < s) {
            that.viewRecord(rect.id, "view")
            index = i;
            scrolls = scroll
          }
        }
      } else {
        for (let i = index; i >= 0; i--) {
          let rect = rects[i];
          if (rect && 0 < rect.top && rect.bottom < s) {
            index = i;
            scrolls = scroll
          }
        }
      }
    }).exec()
  },
  //滚动和点击屏幕记录
  viewRecord: function (goodsid, act) {
    let that = this;
    let params = {
      name: "ltxx_buyer",
      page: 'group_dragon',
      position: '',
      productid: goodsid,
      userid: that.data.user_id,
      storeid: that.data.store_id,
      act: act,
      env: getApp().globalData.env
    }
    Record_server.recordstat(params, function () { });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
   
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
    * 页面相关事件处理函数--监听用户下拉动作
    */
  onPullDownRefresh: function () {
    let that = this;
    that.setData({
      groupList: [], //群接龙
      endGroupBloon: true, //群接龙事件节流
      loadGroupBloon: true, //群接龙是否到底
      nomore: true, //群接龙是否没有
      pageGroup: 0, //群接龙页数
      hottodyList: [], // 2.12.0今日热销
      pageHot: 0,
      endHotBloon: true,
      loadHotBloon: true,
    })
    that.getGroupList(1);
    that.swiperGroup();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let that = this;
    if (that.data.loadGroupBloon && that.data.endGroupBloon) {
      that.setData({
        endGroupBloon: false
      })
      that.getGroupList(that.data.pageGroup);
    } else if (that.data.loadHotBloon && that.data.endHotBloon) {
      that.setData({
        endHotBloon: false
      })
      that.storeListHot(that.data.pageHot)
    }
  },
})